﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Silverlight;
using System.Xml;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace SalaryChannel
{
    public partial class ChannelReport : UserControl
    {
        private  ReportService.ReportServiceClient _reportService = null;
        private  OperationContext _reportPC = null;
        public  ReportService.ReportServiceClient ReportService
        {
            get
            {
                if (_reportService == null)
                {
                    _reportService = new SalaryChannel.ReportService.ReportServiceClient();
                    OperationContext.Current = new OperationContext((IContextChannel)_reportService.InnerChannel);
                    MessageHeader header = MessageHeader.CreateHeader("uafcztga", "", "yangch_ts");
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    header = MessageHeader.CreateHeader("xufasft", "", "sc.yc.cobs");
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);

                    _reportPC = OperationContext.Current;
                }
                else
                {
                    OperationContext.Current = _reportPC;
                }
                return _reportService;
            }
        }

        public ChannelReport()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ChannelReport_Loaded);
            this.ReportTypeCBox.SelectionChanged += new SelectionChangedEventHandler(ReportTypeCBox_SelectionChanged);

            ReportService.GetValidReportCompleted += new EventHandler<SalaryChannel.ReportService.GetValidReportCompletedEventArgs>(ReportService_GetValidReportCompleted);
            ReportService.GetReportByIDCompleted += new EventHandler<SalaryChannel.ReportService.GetReportByIDCompletedEventArgs>(ReportService_GetReportByIDCompleted);
            ReportService.GetAreaCompleted += new EventHandler<SalaryChannel.ReportService.GetAreaCompletedEventArgs>(ReportService_GetAreaCompleted);
            ReportService.GetReportByIDIntoFileCompleted += new EventHandler<SalaryChannel.ReportService.GetReportByIDIntoFileCompletedEventArgs>(ReportService_GetReportByIDIntoFileCompleted);
        }

        

        void ReportService_GetAreaCompleted(object sender, SalaryChannel.ReportService.GetAreaCompletedEventArgs e)
        {
            try
            {

                if (e.Result != null)
                {
                    if (AreaCBox.Items.Count != 0)
                    {
                        AreaCBox.Items.Clear();
                    }
                    AreaCBox.Items.Add("[0]全部");
                    foreach (string s in e.Result)
                    {
                        AreaCBox.Items.Add(s);
                    }

                    if (App.IsAuth(13))
                    {
                        this.ChannelIDTB.Text = string.Empty;
                        this.ChannelIDTB.IsReadOnly = false;
                        this.AreaCBox.IsEnabled = true;
                        this.AreaCBox.SelectedIndex = 0;
                    }
                    else if (App.IsAuth(12))
                    {
                        this.AreaCBox.SelectedIndex = -1;
                        for (int i = 0; i < this.AreaCBox.Items.Count; i++)
                        {
                            if (this.AreaCBox.Items[i].ToString().Contains(App.CurrentUser.CountyCode))
                            {
                                this.AreaCBox.SelectedIndex = i;
                                break;
                            }
                        }
                        this.AreaCBox.IsEnabled = false;
                        this.ChannelIDTB.Text = string.Empty;
                        this.ChannelIDTB.IsReadOnly = false;
                    }
                    else if (App.IsAuth(10))
                    {
                        this.AreaCBox.SelectedIndex = 0;
                        this.AreaCBox.IsEnabled = false;
                        this.ChannelIDTB.Text = App.CurrentUser.ChannelID;
                        this.ChannelIDTB.IsReadOnly = true;

                    }
                }
            }
            catch 
            {
            }
        }

        void ReportTypeCBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ReportTypeCBox.SelectedIndex >= 0)
            {
                try
                {
                    ReportService.GetValidReportAsync(ReportTypeCBox.SelectedIndex+1);
                }
                catch
                {
                    App.MessageBox.ShowDialog("连接服务器失败");
                }
            }
        }

        void ReportService_GetReportByIDCompleted(object sender, SalaryChannel.ReportService.GetReportByIDCompletedEventArgs e)
        {
            loading.Stop();
            if (e.Result == null)
            {
                App.MessageBox.ShowDialog("获取信息失败");

            }
            else
            {
                try
                {
                    Silverlight.DataTable table = Xml2Table.Convert(e.Result.TableNamek__BackingField,
                                e.Result._columns, e.Result.XmlStringk__BackingField);
                    if (table.Rows.Count == 0)
                    {
                        App.MessageBox.ShowDialog("没有查询到数据");
                        this.ReportGrid.ItemsSource = null;
                        return;
                    }
                    this.ReportGrid.ItemsSource = table.GetBindableData(new Connector());
                }
                catch 
                {
                    this.ReportGrid.ItemsSource = null;

                    App.MessageBox.ShowDialog("绑定信息失败");
                }
            }
        }

        void ReportService_GetValidReportCompleted(object sender, SalaryChannel.ReportService.GetValidReportCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                if(this.ReportCBox.Items.Count!=0)
                {
                    this.ReportCBox.Items.Clear();
                }
                foreach (string s in e.Result)
                {
                    this.ReportCBox.Items.Add(s);
                }

            }
        }

        

        public void Initiallize()
        {
            this.TimeTB.Text = string.Empty;
            this.ChannelIDTB.Text = string.Empty;
            this.AreaCBox.SelectedIndex = -1;
            this.ReportGrid.ItemsSource = null;
            this.ExportBtn.Visibility = App.IsAuth(15) ? Visibility.Visible : Visibility.Collapsed;

            this.DownloadBtn.Visibility = Visibility.Collapsed;

           

            try
            {
                if (AreaCBox.Items.Count == 0)
                {
                    ReportService.GetAreaAsync(App.CurrentUser.CityCode);
                }
            }
            catch
            {
            }
            
            
        }
        void ChannelReport_Loaded(object sender, RoutedEventArgs e)
        {

            this.ReportTypeCBox.Items.Add("日报表");
            this.ReportTypeCBox.Items.Add("月报表");
           
        }

        private void QueryBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ReportCBox.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择一个报表");
                return;
            }
            if (string.IsNullOrEmpty(TimeTB.Text))
            {
                App.MessageBox.ShowDialog("请输入一个统计日期，如：20111211或201112");
                return;
            }

            if(AreaCBox.SelectedItem== null)
            {
                App.MessageBox.ShowDialog("请选择一个县区");
                return;
            }
            string date =  TimeTB.SelectedDate.Value.Year.ToString() + TimeTB.SelectedDate.Value.Month.ToString("00");
            if (ReportTypeCBox.SelectedIndex == 0)
            {
                date += TimeTB.SelectedDate.Value.Day.ToString("00");
            }

            try
            {
                ReportService.GetReportByIDAsync(
                       DataHelper.GetIDOFIDAndName(ReportCBox.SelectedItem.ToString()),
                       this.ChannelIDTB.Text,
                       AreaCBox.SelectedIndex == 0 ? string.Empty : DataHelper.GetIDOFIDAndName(AreaCBox.SelectedItem.ToString()).ToString(),
                       date);
                loading.Show();
            }
            catch 
            {
                loading.Show();
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        private void ExportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ReportCBox.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择一个报表");
                return;
            }
            if (string.IsNullOrEmpty(TimeTB.Text))
            {
                App.MessageBox.ShowDialog("请输入一个统计日期，如：20111211或201112");
                return;
            }

            if (AreaCBox.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择一个县区");
                return;
            }
            string date = TimeTB.SelectedDate.Value.Year.ToString() + TimeTB.SelectedDate.Value.Month.ToString("00");
            if (ReportTypeCBox.SelectedIndex == 0)
            {
                date += TimeTB.SelectedDate.Value.Day.ToString("00");
            }
            try
            {
                ReportService.GetReportByIDIntoFileAsync(
                       DataHelper.GetIDOFIDAndName(ReportCBox.SelectedItem.ToString()),
                       this.ChannelIDTB.Text,
                       AreaCBox.SelectedIndex == 0 ? string.Empty : DataHelper.GetIDOFIDAndName(AreaCBox.SelectedItem.ToString()).ToString(),
                       date);
                loading.Show();
            }
            catch
            {
                loading.Show();
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        void ReportService_GetReportByIDIntoFileCompleted(object sender, SalaryChannel.ReportService.GetReportByIDIntoFileCompletedEventArgs e)
        {
            loading.Stop();
            try
            {
                ExportBtn.IsEnabled = true;
                if (e.Result == string.Empty)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");
                }
                else if (e.Result == "-1")
                {
                    App.MessageBox.ShowDialog("导出失败，请联系管理员");
                }
                else
                {
                    // System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(ee.Result, UriKind.Relative), "_blank");
                    //(ee.Result);// new Uri(ee.Result, UriKind.Relative);
                    string uri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
                    //App.MessageBox.ShowDialog(uri);
                    if (!uri.ToLower().EndsWith("salary/"))
                    {
                        if (!uri.EndsWith("/'"))
                        {
                            uri = uri.Remove(uri.LastIndexOf('/') + 1) + e.Result;
                        }
                    }
                    else
                    {
                        uri += e.Result;
                    }
                    DownloadBtn.NavigateUri = new Uri(uri);

                    DownloadBtn.Visibility = Visibility.Visible;
                }

            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("导出异常，" + ex.Message);
            }
        }
    }
}
